package main.技巧;

import java.util.Arrays;

/**
 * @author tmh
 * @date 2024/9/22 15:36
 * @description
 */
public class T75颜色分类 {
    public static void main(String[] args) {
        sortColors(new int[]{2, 0, 2, 1, 1, 0});
    }

    public static void sortColors(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length; j++) {
                if (nums[i] < nums[j]) {
                    int temp = nums[j];
                    nums[j] = nums[i];
                    nums[i] = temp;
                }
            }
        }
        System.out.println(Arrays.toString(nums));
    }

    //借助循环不变量，用三个区间来装我们的元素
    //[0,p0),[p0,i),(p2,len-1],三个区间分别装0 1 2

    public void sortColors2(int[] nums) {
        //初始化三个指针 让三个区间一开始为空区间
        int p0 = 0;
        int p2 = nums.length - 1;
        int i = 0;
        while (i <= p2) {
            if (nums[i] == 2) {
                swap(nums, i, p2);
                p2--;
            } else if (nums[i] == 1) {
                i++;
            } else if (nums[i] == 0) {
                swap(nums, p0, i);
                p0++;
                i++;
            }
        }
    }

    public void swap(int[] nums, int l, int r) {
        int temp = nums[l];
        nums[l] = nums[r];
        nums[r] = temp;
    }
}
